﻿// SilverlightBridge
// Copyright (c) 2009
// by OpenLight Group
// http://openlightgroup.net/
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
//
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.

// For upload control see the included License.txt
using System;
using System.Linq;
using System.IO;
using System.Web;
using System.Collections.Generic;

namespace SilverlightFileManager
{
    public delegate void FileUploadCompletedEvent(object sender, FileUploadCompletedEventArgs args);

    #region FileUploadCompletedEventArgs
    public class FileUploadCompletedEventArgs
    {
        public string FileName { get; set; }
        public string FilePath { get; set; }

        public FileUploadCompletedEventArgs() { }

        public FileUploadCompletedEventArgs(string fileName, string filePath)
        {
            FileName = fileName;
            FilePath = filePath;
        }
    }
    #endregion

    #region FileUploadSettings
    public class FileUploadSettings
    {
        public bool Authendicated { get; set; }
        public string UploadPath { get; set; }
    }
    #endregion

    #region class FileUploadProcess
    public class FileUploadProcess
    {
        public event FileUploadCompletedEvent FileUploadCompleted;

        #region ProcessRequest
        public void ProcessRequest(HttpContext context)
        {
            // ** Values passed in the Header
            // p = portal
            // m = moduleid
            // u = UserId
            // f = folderid
            // tp = password

            string strPortalID = context.Request.QueryString["p"];
            string strModuleID = context.Request.QueryString["m"];
            string strUserId = context.Request.QueryString["u"];
            string strFolderID = context.Request.QueryString["f"];
            string strPassword = context.Request.QueryString["tp"];
            string strIPAddress = context.Request.UserHostAddress;      

            // Other values passed

            string Originalfilename = context.Request.QueryString["filename"];
            bool complete = string.IsNullOrEmpty(context.Request.QueryString["Complete"]) ? true : bool.Parse(context.Request.QueryString["Complete"]);
            bool getBytes = string.IsNullOrEmpty(context.Request.QueryString["GetBytes"]) ? false : bool.Parse(context.Request.QueryString["GetBytes"]);
            long startByte = string.IsNullOrEmpty(context.Request.QueryString["StartByte"]) ? 0 : long.Parse(context.Request.QueryString["StartByte"]); ;

            // Convert values
            int intPortalID = Convert.ToInt32(strPortalID);
            int intModuleID = Convert.ToInt32(strModuleID);
            int intUserId = Convert.ToInt32(strUserId);
            int intFolderID = Convert.ToInt32(strFolderID);

            FileUploadSettings objFileUploadSettings = GetSettings(context, intPortalID, intModuleID, intUserId, strPassword, strIPAddress);

            if (objFileUploadSettings.Authendicated)
            {
                if (CanUploadTotheFolder(intUserId, intFolderID))
                {
                    Utility Utility = new Utility();
                    string strExtension = System.IO.Path.GetExtension(Originalfilename);
                    string strFileDirectory = String.Format(@"{0}\{1}\{2}", objFileUploadSettings.UploadPath, strPortalID, strUserId);
                    string filePath = Path.Combine(strFileDirectory, Originalfilename);

                    if (getBytes)
                    {
                        Utility.EnsureDirectory(new System.IO.DirectoryInfo(strFileDirectory));
                        FileInfo fi = new FileInfo(filePath);
                        if (!fi.Exists)
                            context.Response.Write("0");
                        else
                            context.Response.Write(fi.Length.ToString());

                        context.Response.Flush();
                        return;
                    }
                    else
                    {
                        if (startByte > 0 && File.Exists(filePath))
                        {
                            using (FileStream fs = File.Open(filePath, FileMode.Append))
                            {
                                SaveFile(context.Request.InputStream, fs);
                                fs.Close();
                            }
                        }
                        else
                        {
                            using (FileStream fs = File.Create(filePath))
                            {
                                SaveFile(context.Request.InputStream, fs);
                                fs.Close();
                            }
                        }
                        if (complete)
                        {
                            if (FileUploadCompleted != null)
                            {
                                // Rename the file
                                string Newfilename = String.Format("{0}{1}{2}", Originalfilename.Replace(strExtension, ""), Utility.GetRandomPassword(), strExtension);
                                string OriginalfilePath = Path.Combine(strFileDirectory, Originalfilename);
                                string NewfilePath = Path.Combine(strFileDirectory, Newfilename);
                                FileInfo fi = new FileInfo(filePath);
                                fi.CopyTo(NewfilePath);
                                // Delete the orginal File
                                fi.Delete();

                                // Save File to Database
                                SaveFileToDatabase(intUserId, intFolderID, Originalfilename, Newfilename, strFileDirectory);

                                FileUploadCompletedEventArgs args = new FileUploadCompletedEventArgs(Newfilename, filePath);
                                FileUploadCompleted(this, args);
                            }
                        }
                    }
                }
            }
        }
        #endregion

        #region SaveFile
        private void SaveFile(Stream stream, FileStream fs)
        {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
            {
                fs.Write(buffer, 0, bytesRead);
            }
        }
        #endregion

        #region SaveFileToDatabase
        private void SaveFileToDatabase(int intUserId, int intFolderID, string Originalfilename, string Newfilename, string strFileDirectory)
        {
            SilverlightFileManagerDALDataContext objSilverlightFileManagerDALDataContext = new SilverlightFileManagerDALDataContext();

            // If there is a previous file with the same name in the folder - delete it
            var Existing_FileUpload_File = (from FileUpload_Files in objSilverlightFileManagerDALDataContext.FileUpload_Files
                                            where FileUpload_Files.FolderID == intFolderID
                                            where FileUpload_Files.OriginalFileName == Originalfilename
                                            select FileUpload_Files).FirstOrDefault();

            // If the file is found delete it
            if (Existing_FileUpload_File != null)
            {
                DeleteFileFromFolder(Existing_FileUpload_File.FileID);
            }

            // Add the new file to the database
            FileUpload_File objFileUpload_File = new FileUpload_File();
            objFileUpload_File.FileName = Newfilename;
            objFileUpload_File.FilePath = strFileDirectory;
            objFileUpload_File.FolderID = intFolderID;
            objFileUpload_File.OriginalFileName = Originalfilename;
            objFileUpload_File.UserID = intUserId;

            objSilverlightFileManagerDALDataContext.FileUpload_Files.InsertOnSubmit(objFileUpload_File);
            objSilverlightFileManagerDALDataContext.SubmitChanges();
        }
        #endregion

        #region DeleteFileFromFolder
        private void DeleteFileFromFolder(int intFileID)
        {
            SilverlightFileManagerDALDataContext objSilverlightFileManagerDALDataContext = new SilverlightFileManagerDALDataContext();

            var objFileUpload_Files = (from FileUpload_Files in objSilverlightFileManagerDALDataContext.FileUpload_Files
                                                     where FileUpload_Files.FileID == intFileID
                                                     select FileUpload_Files).FirstOrDefault();

            // Delete file
            if (objFileUpload_Files != null)
            {
                string filePath = Path.Combine(objFileUpload_Files.FilePath, objFileUpload_Files.FileName);
                FileInfo fi = new FileInfo(filePath);
                if (fi.Exists)
                {
                    fi.Delete();
                }
            }

            // Delete from database
            objSilverlightFileManagerDALDataContext.FileUpload_Files.DeleteOnSubmit(objFileUpload_Files);
            objSilverlightFileManagerDALDataContext.SubmitChanges();
        }

        #endregion

        #region GetSettings
        private FileUploadSettings GetSettings(HttpContext context, int intPortalID, int ModuleID, int intUserId, string strPassword, String strIPAddress)
        {
            FileUploadSettings objFileUploadSettings = new FileUploadSettings();
            objFileUploadSettings.Authendicated = false;

            if (IsValidUser(intPortalID, ModuleID, intUserId, strPassword, strIPAddress))
            {
                objFileUploadSettings.Authendicated = true;
                // Get path for Files
                objFileUploadSettings.UploadPath = context.Server.MapPath("~/Upload");
            }

            return objFileUploadSettings;
        }
        #endregion

        #region IsValidUser
        private bool IsValidUser(int PortalID, int ModuleID, int UserID, string Password, string strIPAddress)
        {
            bool boolIsValidUser = false;

            SilverlightBridgeAuthendicationHeader SilverlightBridgeAuthendicationHeader = new SilverlightBridgeAuthendicationHeader();
            SilverlightBridgeAuthendicationHeader.PortalID = PortalID;
            SilverlightBridgeAuthendicationHeader.ModuleId = ModuleID;
            SilverlightBridgeAuthendicationHeader.UserID = UserID;
            SilverlightBridgeAuthendicationHeader.Password = Password;
            SilverlightBridgeAuthendicationHeader.IPAddress = strIPAddress;

            Authendication Authendication = new Authendication(SilverlightBridgeAuthendicationHeader);

            if (!Authendication.IsUserValid())
            {
                boolIsValidUser = false;
            }
            else
            {
                boolIsValidUser = true;
            }

            return boolIsValidUser;
        }
        #endregion

        #region CanUploadTotheFolder
        private bool CanUploadTotheFolder(int UserId, int FolderID)
        {
            bool boolCanUploadTotheFolder = false;

            SilverlightFileManagerDALDataContext objSilverlightFileManagerDALDataContext = new SilverlightFileManagerDALDataContext();

            var Folder = (from FileUpload_Categories in objSilverlightFileManagerDALDataContext.FileUpload_Categories
                          where FileUpload_Categories.UserID == UserId
                          where FileUpload_Categories.CategoryID == FolderID
                          select FileUpload_Categories).FirstOrDefault();

            if (Folder != null)
            {
                boolCanUploadTotheFolder = true;
            }

            return boolCanUploadTotheFolder;
        }
        #endregion
    }
    #endregion
}